package cn.mrlong.base.ktnet.err

import com.google.gson.JsonParseException
import org.json.JSONException
import retrofit2.HttpException
import java.net.ConnectException
import java.net.SocketTimeoutException
import java.net.UnknownHostException
import java.text.ParseException

/**
 * 作者：BINGO
 * 时间：2021/03/26 17:23
 * 异常统一翻译对应的Err
 */
object FactoryException {
    private const val HttpException_MSG = "网络错误"
    private const val ConnectException_MSG = "连接失败"
    private const val JSONException_MSG = "数据解析失败"
    private const val UnknownHostException_MSG = "无法解析该域名"
    public const val SERVER_MSG = "服务器异常，请联系管理员！"
    public const val SERVER_DATA_NULL = "服务器异常！"
    public const val Unknown_MSG = "未知异常"

    /**
     * 解析异常
     *
     * @param e
     * @return
     */
    fun analysisExcetpion(e: Throwable): String {
        var errorMessage = ""
        if (e is HttpException) {
            /*网络异常*/
            errorMessage = HttpException_MSG
        } else if (e is ServerException) {
            /*自定义运行时异常*/
            errorMessage = SERVER_MSG
        } else if (e is ConnectException || e is SocketTimeoutException) {
            /*链接异常*/
            errorMessage = ConnectException_MSG
        } else if (e is JsonParseException || e is JSONException || e is ParseException) {
            /*fastjson解析异常*/
            errorMessage = JSONException_MSG
        } else if (e is UnknownHostException) {
            /*无法解析该域名异常*/
            errorMessage = UnknownHostException_MSG
        } else {
            /*未知异常*/
            errorMessage = if (null != e.message) e.message!! else Unknown_MSG
        }
        return errorMessage
    }
}